package com.liaowei.system.controller;

import com.liaowei.common.BaseResponse;
import com.liaowei.common.ErrorCode;
import com.liaowei.common.ResultUtils;
import com.liaowei.exception.CustomerException;
import com.liaowei.system.model.vo.FileVO;
import com.liaowei.system.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.google.api.client.util.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@RestController
@RequestMapping("files")
@RequiredArgsConstructor
@Validated
public class FileController {

    private final FileService fileService;


    // 下载
    @GetMapping("download")
    public void download(@RequestParam String path, HttpServletResponse response) throws UnsupportedEncodingException {
        OutputStream os = null;
        InputStream is = null;
        int pointIndex = path.lastIndexOf(".");
        String fileName = "resource" + path.substring(pointIndex,path.length());

        try {
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            response.setContentType("application/x-download;charset=utf-8");
            //Content-Disposition中指定的类型是文件的扩展名，并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的，点保存后，文件以filename的值命名，
            // 保存类型以Content中设置的为准。注意：在设置Content-Disposition头字段之前，一定要设置Content-Type头字段。
            //把文件名按UTF-8取出，并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码，中文不要太多，最多支持17个中文，因为header有150个字节限制。
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            //读取流
            File f = new File(path);
            is = new FileInputStream(f);
            if (is == null) {
                System.out.println("下载附件失败，请检查文件“" + fileName + "”是否存在");
            }
            //复制
            IOUtils.copy(is, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }
        //文件的关闭放在finally中
        finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 根据tagId查询资源列表
    @GetMapping("list/{tagId}")
    public BaseResponse<List<FileVO>> fileListByTagId(@PathVariable Long tagId) {
        return ResultUtils.success(fileService.searchFileListByTagId(tagId));
    }
}
